package com.css.fxfzaqbz.modules.callJcData.controller;

import com.css.fxfzaqbz.base.response.RestResponse;
import com.css.fxfzaqbz.base.upload.entity.AttachmentInfoEntity;
import com.css.fxfzaqbz.base.upload.service.AttachmentInfoService;
import com.css.fxfzaqbz.modules.data.entity.Site;
import com.css.fxfzaqbz.modules.data.queryParams.SiteQueryParams;
import com.css.fxfzaqbz.modules.callJcData.service.SiteService;
import com.css.fxfzaqbz.modules.maps.queryParams.MapQueryParams;
import com.css.fxfzaqbz.modules.maps.service.SiteMapService;
import com.css.fxfzaqbz.util.FileUtil2;
import com.css.fxfzaqbz.util.PlatformObjectUtils;
import com.css.fxfzaqbz.web.PlatformSessionContext;
import com.css.fxfzaqbz.zcpt.sys.service.impl.SUserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 3.3.1构造环境数据管理子模块 -表4重点场所数据表单
 */
@RestController
@RequestMapping("/fxfzaqbz/data")
@Slf4j
public class SiteController {
    @Resource
    SiteService siteService;

    @Resource
    SiteMapService siteMapService;//地图使用

    @Resource
    SUserServiceImpl sUserServiceImpl;

    @Resource
    private AttachmentInfoService attachmentInfoService;

    //获取配置文件的上传文件路径
    @Value("${file.upload.path}")
    private String uploadPath;

    /**
     * 新增site
     * @param site
     * @return
     */
    @PostMapping("/saveSite")
    public RestResponse saveSite (@RequestBody Site site , HttpServletRequest request){
        RestResponse restResponse = null ;
        try{
            String userID = PlatformSessionContext.getUserID();
            site.setCreateUser(userID);

            restResponse = RestResponse.succeed(siteService.saveSite(site,request));
        }catch (Exception e){
            log.error("新增重点场所数据失败",e);
            restResponse = RestResponse.fail("新增活重点场所数据失败!");
        }
        return restResponse;
    }

    /**
     * 全查询  模糊查询未设定条件
     * @param request
     * @param queryParams
     * @return
     */
    @GetMapping("/getAllSite")
    public RestResponse getAllSite(HttpServletRequest request, SiteQueryParams queryParams){

        RestResponse restResponse = null;
        try{
            //int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            //int pageSize = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            //查询条件
            String province = request.getParameter("province");
            String city = request.getParameter("city");
            String county = request.getParameter("county");
            String number = request.getParameter("number");
            String name = request.getParameter("name");
            String fileUuid = request.getParameter("fileUuid");//当前数据所在文件UUID
            String confirm = request.getParameter("confirm");//是否查询已提交数据0未提交1已提交
            queryParams.setSsProvince(province);
            queryParams.setSsCity(city);
            queryParams.setSsCounties(county);
            queryParams.setSsNumber(number);
            queryParams.setSsJzwmc(name);
            queryParams.setSsFileuuid(fileUuid);
            queryParams.setSsConfirm(confirm);
            //queryParams.setCurPage(Integer.parseInt(PlatformPageUtils.CUR_PAGE_DEF));
            //queryParams.setPageSize(Integer.parseInt(PlatformPageUtils.PAGE_SIZE_DEF));
            restResponse = RestResponse.succeed(siteService.getAllSite(queryParams));
        }catch (Exception e){
            log.error("查询重点场所数据失败!",e);
            restResponse = RestResponse.fail("查询重点场所数据失败");
        }
        return restResponse;
    }

    /**
     * 根据id查询Site数据
     * @param id
     * @return
     */
    @GetMapping("/getSite/{id}")
    public RestResponse<Site> getSite(@PathVariable("id") String id) {
        RestResponse restResponse = null;
        try{
            Map<String,Object> map=new HashMap<>();
            Site site = siteService.getSiteById(id);
            map.put("site",site);
            if (StringUtils.isNotBlank(site.getSsZp())){
                List<AttachmentInfoEntity> zplist=new ArrayList<>();
                String[] split = site.getSsZp().split(",");
                for (String s : split) {
                    AttachmentInfoEntity zpAttach = attachmentInfoService.getAttach(s);
                    zplist.add(zpAttach);
                }
                map.put("zplist",zplist);
            }
            if (StringUtils.isNotBlank(site.getSsSgt())){
                List<AttachmentInfoEntity> sgtlist=new ArrayList<>();
                    String[] split = site.getSsSgt().split(",");
                    for (String s : split) {
                        AttachmentInfoEntity zpAttach = attachmentInfoService.getAttach(s);
                        sgtlist.add(zpAttach);
                    }
                map.put("sgtlist",sgtlist);
            }
            if (StringUtils.isNotBlank(site.getSsXfjhpsj())){
                List<AttachmentInfoEntity> xfjlist=new ArrayList<>();
                String[] split = site.getSsXfjhpsj().split(",");
                for (String s : split) {
                    AttachmentInfoEntity zpAttach = attachmentInfoService.getAttach(s);
                    xfjlist.add(zpAttach);
                }
                map.put("xfjlist",xfjlist);
            }
            restResponse = RestResponse.succeed(map);
        }catch (Exception e){
            log.error("获取重点场所数据失败!",e);
            restResponse = RestResponse.fail("获取重点场所数据失败!");
        }
        return restResponse;
    }



    /**
     * 根据名字查询Site数据
     * @param ssJzwmc
     * @return
     */
    // @GetMapping("/getSiteByName/{ssJzwmc}")
    @GetMapping("/getSiteByName")
    public RestResponse<Site> getSiteByName(String ssJzwmc) {
        RestResponse restResponse = null;
        try{
            boolean flag = siteService.getSiteByName(ssJzwmc);
            if(!flag){
                restResponse = RestResponse.succeed(flag);
                restResponse.setMessage("【重点场所数据管理】中无该重点目标信息，是否添加相关数据？");
            }else {
                restResponse = RestResponse.succeed(flag);
            }

        }catch (Exception e){
            log.error("获取重点场所数据失败!",e);
            restResponse = RestResponse.fail("获取重点场所数据失败!");
        }
        return restResponse;
    }



    /**
     * 逻辑删除，修改数据标志位
     * @param ids
     * @return
     */
    @PostMapping("/delSite/{ids}")
    public RestResponse deleteSite(@PathVariable("ids") List<String> ids) {
        RestResponse restResponse = null;
        try{
            String userID = PlatformSessionContext.getUserID();
            siteService.deleteSites(ids,userID);
            restResponse = RestResponse.succeed();
        }catch (Exception e){
            log.error("删除重点场所数据失败!",e);
            restResponse = RestResponse.fail("删除重点场所数据失败!");
        }
        return restResponse;
    }

    /**
     * 修改
     * @param site
     * @return
     */
    @PostMapping("/updateSite")
    public RestResponse<Site> updateActiveFaultData(@RequestBody Site site)  {
        RestResponse restResponse = null;
        try{
            //String sUser = sUserServiceImpl.getSUser(PlatformSessionContext.getUserID());
            //SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
            //String userName = userInfo.getUserName();
            String userID = PlatformSessionContext.getUserID();
            //判断是否数据完整提交
            String ssConfirm = "0";
            if(!PlatformObjectUtils.isEmpty(site.getSsZp())
                    && !PlatformObjectUtils.isEmpty(site.getSsSgt())
                    && !PlatformObjectUtils.isEmpty(site.getSsXfjhpsj())) {//是否全部上传图片
                ssConfirm = "1";//数据完整提交
            }
            site.setSsConfirm(ssConfirm);

            //restResponse = RestResponse.succeed(siteService.updateSite(site,userID));

            //zyt--更新数据
            restResponse = RestResponse.succeed(siteMapService.newUpdateSite(site,userID));
        }catch (Exception e){
            log.error("修改重点场所数据失败!",e);
            restResponse = RestResponse.fail("修改重点场所数据失败!");
        }
        return restResponse;
    }

    /**
     * 导出表内数据
     * @param response
     * @throws IOException
     */
    @PostMapping("/exportExcelSite")
    public void exportExcel(HttpServletResponse response ) throws IOException {
        RestResponse restResponse = null;
        try{
            List<Site> list  = siteService.getAll();
            FileUtil2.exportExcel(list, "重点场所数据", "sheet", Site.class, "Site", response);
            restResponse = RestResponse.succeed("导出成功");
        }catch (Exception e){
            log.error("导出失败",e);
            restResponse = RestResponse.fail("导出失败");
        }
    }

    /**
     * 导入数据
     * @throws IOException
     */
    @PostMapping("/importExcelSite")
    public RestResponse importExcel(@RequestParam("files") MultipartFile[] files, MapQueryParams queryParams) throws IOException {
        RestResponse restResponse = null;
        try{
            //循环处理每一个文件
            for (MultipartFile file : files) {
                siteService.importExcel(file);
            }
            restResponse = RestResponse.succeed("导入成功");
        }catch (Exception e){
            log.error("导入失败",e);

        }
        return restResponse ;
    }


//    /* @param response
//     * @throws IOExceptiond
//     * 文件下载
//     */
//    @PostMapping("/downLoadSiteFile")
//    public void exportExcel(HttpServletResponse response,@RequestParam("attachId") String attachId ) {
//
//        try{
//            System.out.println(attachId);
//            AttachmentInfoEntity attachmentInfoEntity = attachmentInfoRepository.getById(attachId);
//
//            String path = attachmentInfoEntity.getFileDirId()+attachmentInfoEntity.getAttachPath();
//            //String path = "D:\static\2022\09\07\q_1662518879720.png";
//            FileUploadUtil.download(path,response);
//        }catch (Exception e){
//            log.error("下载失败"+e);
//        }
//
//    }

//    @PostMapping("uploadSiteFile")
//    public RestResponse uploadSiteFile(SiteFile siteFile){
//        RestResponse restResponse = null ;
//        try{
//            AttachmentInfoEntity attachmentInfoEntity = attachmentController.uploadFile(siteFile.getFile());
//            Site site =  siteService.updateFile(attachmentInfoEntity,siteFile);
//            restResponse = RestResponse.succeed(site);
//        }catch (Exception e){
//            log.error("上传失败"+e);
//            restResponse = RestResponse.fail("上传失败");
//        }
//        return restResponse;
//    }

    /*zyt修改--start*/
    /**
     * 批量上传文件
     *
     * @param files
     * @return
     */
    @PostMapping("/upload")
    public RestResponse uploadSpaceData(@RequestParam("files") MultipartFile[] files, MapQueryParams queryParams) {
        System.out.println(new Date()+"-----------1.开始上传文件");
        //数据校验
        if (files == null && files.length <= 0) {
            return RestResponse.fail("上传失败，请选择文件");
        }
        String province = queryParams.getProvince(), city = queryParams.getCity(), area = queryParams.getArea();
        //if ("".equals(province) ) return RestResponse.fail("请选择场地所在省份!");
        //if ("".equals(city)) return RestResponse.fail("请选择场地所在城市!");
        //if ("".equals(area)) return RestResponse.fail("请选择场地所在区县!");

        /*//判断是否已上传未保存文件--上传类型（SITE_）
        int fileCount = qhMapFilesService.lookUpMapFiles("0","SITE_","1",province,city,area);
        if(fileCount>0) return RestResponse.succeed("【" + province + "-" + city + "-" + area + "】已上传文件等待数据入库, 若要上传最新数据请第二天在【图层管理】功能中删除数据.");

        //判断是否已上传正在保存文件--上传类型（SITE_）
        fileCount = qhMapFilesService.lookUpMapFiles("2","SITE_","1",province,city,area);
        if(fileCount>0) return RestResponse.succeed("【" + province + "-" + city + "-" + area + "】已上传文件数据正在入库, 若要上传最新数据请第二天在【图层管理】功能中删除数据.");
        */
        //判断是否已存在上传数据
        //int count = qhRiskLevelMapService.lookUpQhRiskLevelMaps(queryParams, true);
        //if (count > 0) return RestResponse.succeed("【" + province + "-" + city + "-" + area + "】已上传数据, 若要上传最新数据请先在【图层管理】功能中删除数据.");

        // 返回的消息
        StringBuilder returnMsg = new StringBuilder();

        String gdbFileName = "";//gdb文件名
        String jxfilename = "";//shp文件名
        String dbffilename = "";
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        String formatDate = df.format(new Date());
        //判断是否为GDB文件
        for (MultipartFile file : files) {
            //获取上传原文件名称
            String oldFileName = file.getOriginalFilename();
            if (oldFileName.equals("gdb")) {//是否存在gdb文件
                String fName = "新建文件地理数据库";
                String postfix = ".gdb";
                String prefix = "SITE_";
                String district = (province == null ? "0" : province) + "_" + (city == null ? "0" : city) + "_" + (area == null ? "0" : area);
                gdbFileName = prefix + "_" + district + "_" + fName + "_" + formatDate + postfix;
                break;
            }
        }

        //循环处理每一个文件
        for (MultipartFile file : files) {
            //获取上传原文件名称
            String oldFileName = file.getOriginalFilename();
            String newFileName = "";
            if(!PlatformObjectUtils.isEmpty(gdbFileName)) {//GDB文件
                newFileName = gdbFileName + "/"+oldFileName;
            }else {//SHP文件
                // 上传后文件名
                String fName = oldFileName.substring(0, oldFileName.indexOf(".")), postfix = oldFileName.substring(oldFileName.indexOf("."));
                String prefix = "SITE_";
                String district = (province == null ? "0" : province) + "_" + (city == null ? "0" : city) + "_" + (area == null ? "0" : area);
                newFileName = prefix + "_" + district + "_" + fName + "_" + formatDate + postfix;
                if (newFileName.contains(".shp") && newFileName.endsWith(".shp")) {
                    jxfilename = newFileName;
                }
                if (oldFileName.contains(".dbf") && oldFileName.endsWith(".dbf")) {
                    dbffilename = newFileName;
                }
            }
            File folder = new File(uploadPath);
            File savefile = new File(uploadPath + newFileName);
            if (!savefile.getParentFile().exists()) {
                savefile.getParentFile().mkdirs();
            }
            try {
                //file.transferTo(savefile);
                //File _file = new File(uploadPath + newFileName);
                //FileUtils.copyInputStreamToFile(file.getInputStream(), _file);
                //上传文件
                file.transferTo(new File(folder, newFileName));
                returnMsg.append(oldFileName);
                returnMsg.append(",");
            } catch (IOException e) {
                e.printStackTrace();
                return RestResponse.fail(oldFileName + "上传失败");
            }
            returnMsg.append(oldFileName);
            returnMsg.append(",");
        }
        System.out.println(new Date()+"-----------2.上传文件成功--"+jxfilename+gdbFileName);
        String resultMsg = returnMsg.substring(0, returnMsg.length() - 1);
        String resMsg = "";
        String userID = PlatformSessionContext.getUserID();//登录用户ID
        if(!PlatformObjectUtils.isEmpty(gdbFileName)) {//GDB文件
            resultMsg = gdbFileName;//返回GDB文件名
            System.out.println(new Date()+"-----------3.开始importGDBFile");
            //resMsg = qhRiskLevelMapService.checkGDBFiles(uploadPath + gdbFileName, province, city, area);
            System.out.println(new Date()+"-----------4.结束importGDBFile");
            if (resMsg.indexOf("spatialReferenceError") != -1) return RestResponse.succeed("请上传正确的CGCS2000坐标系数据.");
        }else{//SHP文件
            System.out.println(new Date()+"-----------3.开始importShapeFile");
            resMsg = siteMapService.checkSHPFiles(uploadPath + jxfilename, province, city, area, formatDate, userID);
            System.out.println(new Date()+"-----------4.结束importShapeFile");
        }
        if(resMsg.indexOf("导入成功") != -1){//上传成功
            System.out.println(new Date()+"-----------5.上传成功." + resMsg);
        }else{
            System.out.println(new Date()+"-----------5.上传失败." + resMsg);
        }
        if (resMsg.indexOf("checkNotCGCS2000") != -1) return RestResponse.succeed("请上传正确的CGCS2000坐标系数据及.prj文件.");
        if (resMsg.indexOf("messyCode") != -1) return RestResponse.succeed("导入.dbf文件的属性的第【" + resMsg.split("#")[1] + "】条数据信息有乱码.");
        if (resMsg.indexOf("fieldNullValue") != -1) return RestResponse.succeed("上传文件中字段值存在空值, 请对照字段说明检查数据的正确性.");
        //if (resMsg.indexOf("PointIsNotInDistrict") != -1) return RestResponse.succeed("存在没有位于 【" + province + city + area + "】 行政边界的数据, 请检查数据的正确性.");
        if (resMsg.indexOf("GeometryIsNotEqualsCoordinate") != -1) return RestResponse.succeed("填报经纬度属性值与Geometry不一致, 请检查数据正确性.");
        if(resMsg.indexOf("fieldNumError")!=-1) return RestResponse.succeed("上传文件中字段数量不符合要求, 请对照字段说明检查数据的正确性.");
        if(resMsg.indexOf("PointOverlapError")!=-1) return RestResponse.succeed("上传文件中数据存在空间位置重叠, 请检查数据的正确性.");
        if(resMsg.indexOf("LonLatOverlapError")!=-1) return RestResponse.succeed("上传文件中数据与已提交数据存在空间位置重叠, 请检查数据的正确性.");
        if (resMsg.indexOf("jglxFormatError") != -1) return RestResponse.succeed("结构类型不符合字段要求，请对照字段说明检查数据的正确性.");
        if (resMsg.indexOf("jzndFormatError") != -1) return RestResponse.succeed("建造年代不符合字段要求，请对照字段说明检查数据的正确性.");
        if (resMsg.indexOf("plmgzcdFormatError") != -1) return RestResponse.succeed("平立面规则程度不符合字段要求，请对照字段说明检查数据的正确性.");
        if (resMsg.indexOf("sfbzFormatError") != -1) return RestResponse.succeed("设防标准不符合字段要求，请对照字段说明检查数据的正确性.");
        if (resMsg.indexOf("wglbFormatError") != -1) return RestResponse.succeed("屋盖类别不符合字段要求，请对照字段说明检查数据的正确性.");
        if (resMsg.indexOf("csFormatError") != -1) return RestResponse.succeed("层数不符合字段要求，请对照字段说明检查数据的正确性.");
        if (resMsg.indexOf("cgFormatError") != -1) return RestResponse.succeed("层高不符合字段要求，请对照字段说明检查数据的正确性.");
        if (resMsg.indexOf("dwmjzjFormatError") != -1) return RestResponse.succeed("单位面积造价不符合字段要求，请对照字段说明检查数据的正确性.");

        return RestResponse.succeed(resultMsg + "上传成功.<br/>" + resMsg);
    }

    //根据ids查询附件列表
    @GetMapping("/getAttachmentInfoEntityList/{ids}")
    public RestResponse<List<AttachmentInfoEntity>> getAttachmentInfoEntityList(@PathVariable("ids") String ids) {
        RestResponse restResponse = null;
        try{
            List<AttachmentInfoEntity> resultList = new ArrayList<AttachmentInfoEntity>();
            if(!PlatformObjectUtils.isEmpty(ids)) {
                String[] idArr = ids.split(",");
                if(idArr.length>0){
                    for(int i=0;i<idArr.length;i++){
                        String id = idArr[i];
                        if(!PlatformObjectUtils.isEmpty(id)) {
                            //根据图片ids查询图片列表
                            AttachmentInfoEntity attach = attachmentInfoService.getAttach(id);
                            if(attach!=null){
                                resultList.add(attach);
                            }
                        }
                    }
                }
            }
            restResponse = RestResponse.succeed(resultList);
        }catch (Exception e){
            log.error("获取重点场所数据失败!",e);
            restResponse = RestResponse.fail("获取重点场所数据失败!");
        }
        return restResponse;
    }
    /*zyt修改--end*/
}